package com.android.support.lib.universal.base;

import java.util.Stack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BaseActivityManager {
	private static BaseActivityManager sInstance;
	private Stack<Activity> mActivityStack;

	private BaseActivityManager() {
	}

	public static BaseActivityManager getInstance() {
		if (null == sInstance) {
			sInstance = new BaseActivityManager();
		}
		return sInstance;
	}

	public static void startActivity(Context cxt, Class<?> clazz) {
		Intent intent = new Intent(cxt, clazz);
		cxt.startActivity(intent);
	}

	public void pushActivity(Activity activity) {
		if (null == mActivityStack) {
			mActivityStack = new Stack<Activity>();
		}
		mActivityStack.push(activity);
	}

	/**
	 * 当前Activity（栈中最后一个压入的）
	 * 
	 * @return
	 */
	public Activity getStackTopActivity() {
		return mActivityStack.lastElement();
	}

	/**
	 * 结束当前的Activity
	 */
	public void finishActivity() {
		finishActivity(getStackTopActivity());
	}

	/**
	 * 结束指定的Activity
	 * 
	 * @param activity
	 */
	public void finishActivity(Activity activity) {
		if (null != activity) {
			try {
				mActivityStack.remove(activity);
				activity.finish();
				activity = null;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("test", "结束指定的Activity异常" + e.getMessage());
			}

		}
	}

	/**
	 * 结束指定类名的Activity
	 * 
	 * @param clazz
	 */
	public void finishActivity(Class<?> clazz) {
		for (Activity activity : mActivityStack) {
			if (activity.getClass().equals(clazz)) {
				finishActivity(activity);
			}
		}
	}

	/**
	 * 结束所有的Activity
	 */
	public void finishAllActivity() {
		for (Activity activity : mActivityStack) {
			if (null != activity) {
				try {
					activity.finish();
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("test", "结束所有的Activity" + e.getMessage());
				}

			}
		}
		mActivityStack.clear();
	}
}
